const { Sequelize, Model, INTEGER } = require('sequelize')
const { db } = require('../core/sequelize')
const { TaskJournal } = require('./taskJournal')
const { User } = require('./user')
const moment = require('moment')
class Task extends Model {
    static async getTaskList(taskId) {
        const taskList = await Task.findAll({
            where: {
                id: taskId
            }
        })
        return taskList
    }
    //static关键字静态方法 不用new 可以直接调用
    static async setTask(taskId, userId) {
        const taskList = await Task.getTaskList(userId)
        // 往日志表插入一条数据
        let result = await TaskJournal.creatTaskJournal(taskId, userId)
        if (result[1]) {
            // 完成之后增加用户表的积分
            await User.setIntegral(userId, taskList.taskNumber)
            await Task.update(
                {
                    task_state: 1//要修改的数据
                },
                {
                    where: { id: taskId } //查询修改项的条件
                }
            )
            return true
        } else {
            return false
        }

    }
    static async getList(userId) {
        // where查询
        const taskList = await Task.findAll({
            // where: {
            //     userId
            // }
        })
        // 从日志表中对比任务表 判断当前是否已经完成当天的任务
        for (let index = 0; index < taskList.length; index++) {
            let item = taskList[index];
            const state = await TaskJournal.getList(userId, moment().format("YYYY-MM-DD"), item.id)
            item.taskState = state.length ? 1 : 0
            await Task.update(
                {
                    taskState: item.taskState //要修改的数据
                },
                {
                    where: { id: item.id } //查询修改项的条件
                }
            )

        }
        return taskList
    }
}
Task.init(
    {
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true, //设置主键
            autoIncrement: true,
        },
        taskName: Sequelize.STRING,
        taskNumber: Sequelize.INTEGER,
        taskState: Sequelize.INTEGER,
        taskIcons: Sequelize.INTEGER,
        userId: Sequelize.INTEGER,
    },
    {
        // underscored: true,
        sequelize: db,
        modelName: 'task', timestamps: false
    }
)
module.exports = { Task }
